<template>
  <el-container>

    <el-header style="height: auto">
      <el-form :model="queryInfo" ref="queryForm" size="small" :inline="true">
        <el-form-item prop="userName">
          <el-input v-model="queryInfo.userName" @keyup.enter.native="$event.target.blur"
                    placeholder="搜索登录名"
                    prefix-icon="el-icon-search"></el-input>
        </el-form-item>
        <el-form-item prop="trueName">
          <el-input v-model="queryInfo.trueName" @keyup.enter.native="$event.target.blur"
                    placeholder="搜索姓名" prefix-icon="el-icon-search"
                    style="margin-left: 5px"></el-input>
        </el-form-item>
        <el-form-item prop="status">
          <el-select clearable v-model="queryInfo.status" placeholder="请选择账号状态" style="margin-left: 5px; width: 150px">
            <el-option
              v-for="item in status"
              :key="item.type"
              :label="item.info"
              :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="dateRange">
          <el-date-picker v-model="dateRange"
                          type="datetimerange"
                          align="right"
                          unlink-panels
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          :picker-options="pickerOptions"
                          @change="dateRangeChange"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          style="margin-left: 5px">
          </el-date-picker>
        </el-form-item>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" style="margin-left: 5px" icon="el-icon-search" @click="getUserInfo"
                   v-hasPermi="['system:user:query']">查询
        </el-button>
      </el-form>
      <el-row style="margin-top: 5px">
        <el-button type="primary" style="margin-left: 5px" icon="el-icon-plus" @click="showAddDialog"
                   v-hasPermi="['system:user:add']">添加
        </el-button>
        <el-button type="success" style="margin-left: 5px" icon="el-icon-upload2" @click="exportToExcel"
                   v-hasPermi="['system:user:export']">导出
        </el-button>
        <el-button type="info" style="margin-left: 5px" icon="el-icon-download" @click="showImportDialog"
                   v-hasPermi="['system:user:import']">导入
        </el-button>
        <!--操作的下拉框-->
        <el-select @change="selectChange" clearable v-if="selectedInTable.length !== 0" v-model="selected"
                   :placeholder="'已选择' + selectedInTable.length + '项'" style="margin-top: 5px;">

          <el-option value="on" v-hasPermi="['system:user:statusOn']">
            <span style="float: left">启用</span>
            <span style="float: right; color: #8492a6; font-size: 13px">on</span>
          </el-option>
          <el-option value="off" v-hasPermi="['system:user:statusOff']">
            <span style="float: left">禁用</span>
            <span style="float: right; color: #8492a6; font-size: 13px">off</span>
          </el-option>
          <el-option value="delete" v-hasPermi="['system:user:remove']">
            <span style="float: left">删除</span>
            <span style="float: right; color: #8492a6; font-size: 13px">delete</span>
          </el-option>

        </el-select>
      </el-row>
    </el-header>

    <el-main>

      <el-table
        v-hasPermi="['system:user:query']"
        ref="userTable"
        :row-key="userRowKeys"
        highlight-current-row
        v-loading="loading"
        :data="userInfo"
        tooltip-effect="dark"
        style="width: 100%"
        height="91%"
        @selection-change="handleSelectionChange"
        :default-sort="{prop: 'userName', order: 'ascending'}">

        <el-table-column align="center"
                         type="selection"
                         :reserve-selection="true"
                         width="55"
                         :selectable="canSelect">
        </el-table-column>

        <el-table-column align="center"
                         prop="userName"
                         sortable
                         label="用户名">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <p>{{ scope.row.remark }}</p>
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.userName }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>

        <el-table-column align="center"
                         prop="trueName"
                         sortable
                         label="姓名">
        </el-table-column>

        <el-table-column align="center"
                         prop="email"
                         label="电子邮箱">
        </el-table-column>

        <el-table-column align="center"
                         prop="phonenumber"
                         label="电话">
        </el-table-column>

        <el-table-column align="center"
                         label="性别"
                         width="55">
          <template slot-scope="scope">
            {{ scope.row.sex == 0 ? '男' : scope.row.sex == 1 ? '女' : '未知' }}
          </template>
        </el-table-column>

        <el-table-column align="center"
                         label="创建时间">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>

        <el-table-column align="center"
                         label="修改时间">
          <template slot-scope="scope">
            {{ scope.row.updateTime }}
          </template>
        </el-table-column>

        <el-table-column align="center"
                         label="状态">
          <template slot-scope="scope">
            <i v-if="scope.row.status == 0" class="el-icon-check"
               style="font-size: 20px; background: #E8F4FF; color: #1890FF"></i>
            <i v-else class="el-icon-close" style="font-size: 20px; background: #FFEDED; color: #FF4949"></i>
          </template>
        </el-table-column>

        <el-table-column
          fixed="right"
          align="center"
          label="操作">
          <template slot-scope="scope" v-if="scope.row.userId !== 1">
            <el-button @click="showDeleteUserDialog(scope.row)" type="text" size="small"
                       v-hasPermi="['system:user:remove']">删除
            </el-button>
            <el-button @click="showUpdateDialog(scope.row)" type="text" size="small" v-hasPermi="['system:user:edit']">
              修改
            </el-button>
            <el-button @click="showRoleDialog(scope.row)" type="text" size="small" v-hasPermi="['system:user:addRole']">
              分配角色
            </el-button>
          </template>
        </el-table-column>

      </el-table>

      <!--分页-->
      <el-pagination style="margin-top: 25px"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryInfo.pageNo"
                     :page-sizes="[10, 20, 30, 50]"
                     :page-size="queryInfo.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>

    </el-main>

    <el-dialog title="添加用户" :visible.sync="addTableVisible" width="30%" @close="resetAddForm"
               :close-on-click-modal="false"
               center>

      <el-form :model="addForm" :rules="addFormRules" ref="addForm">

        <el-form-item label="用户名" prop="userName">
          <el-input v-model="addForm.userName"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password" show-password></el-input>
        </el-form-item>

        <el-form-item label="真实姓名" prop="trueName">
          <el-input v-model="addForm.trueName"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="addForm.sex">
            <el-radio label=0>男</el-radio>
            <el-radio label=1>女</el-radio>
            <el-radio label=2>未知</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="addForm.phonenumber"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="addForm.remark"></el-input>
        </el-form-item>

        <el-form-item label="账号状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择账号状态">
            <el-option label="有效" value="0"></el-option>
            <el-option label="无效" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改用户" :visible.sync="updateVisible" width="30%" :close-on-click-modal="false"
               @close="resetUpdateForm"
               center>

      <el-form :model="updateForm" :rules="updateFormRules" ref="updateForm">

        <el-form-item label="用户名" prop="userName">
          <el-input v-model="updateForm.userName" disabled></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="updateForm.password" type="password" show-password placeholder="不更改请留空"></el-input>
        </el-form-item>

        <el-form-item label="真实姓名" prop="trueName">
          <el-input v-model="updateForm.trueName"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="updateForm.sex">
            <el-radio label=0>男</el-radio>
            <el-radio label=1>女</el-radio>
            <el-radio label=2>未知</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="updateForm.phonenumber"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updateForm.email"></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="updateForm.remark"></el-input>
        </el-form-item>

        <el-form-item label="账号状态" prop="status">
          <el-select v-model="updateForm.status" placeholder="请选择账号状态">
            <el-option label="有效" value="0"></el-option>
            <el-option label="无效" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="updateVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="导入用户" :visible.sync="ImportVisible" width="400px" append-to-body center
               :close-on-click-modal="false">
      <el-upload
        class="upload-demo"
        ref="upload"
        :on-change="handleChange"
        :on-exceed="handleExceed"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        :on-success="handleFileSuccess"
        :action="'http://localhost:8888/sysUser/importData?updateSupport=' + this.updateSupport"
        accept=".xlsx, .xls"
        :headers="headers"
        :file-list="fileListUpload"
        :limit="limitUpload"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-centeor" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="updateSupport"/>
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="ImportVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="roleDialogVisible" width="80%" center :close-on-click-modal="false">
      <el-row>
        <el-input v-model="roleQueryInfo.roleName" @keyup.enter.native="$event.target.blur"
                  placeholder="搜索角色名"
                  prefix-icon="el-icon-search"></el-input>
        <el-select clearable v-model="roleQueryInfo.status" placeholder="请选择角色状态" style="margin-left: 5px">
          <el-option
            v-for="item in status"
            :key="item.type"
            :label="item.info"
            :value="item.type">
          </el-option>
        </el-select>
        <el-button type="primary" style="margin-left: 5px" icon="el-icon-search" @click="getRoleInfo">查询</el-button>
        <el-button type="primary" @click="addRoleToUser" style="float: right">提交{{
            selectedRoleTable.length
          }}项
        </el-button>
      </el-row>

      <el-table
        ref="roleTable"
        :row-key="roleRowKeys"
        highlight-current-row
        v-loading="roleLoading"
        :border="true"
        :data="roleInfo"
        tooltip-effect="dark"
        style="width: 100%; margin-top: 10px"
        @selection-change="handleRoleSectionChange"
        :default-sort="{prop: 'roleName', order: 'ascending'}">

        <el-table-column align="center"
                         type="selection"
                         :reserve-selection="true"
                         width="55">
        </el-table-column>

        <el-table-column align="center"
                         prop="roleName"
                         sortable
                         label="角色名">
        </el-table-column>

        <el-table-column align="center"
                         prop="roleKey"
                         sortable
                         label="角色编码">
        </el-table-column>

        <el-table-column align="center"
                         label="生效时间">
          <template slot-scope="scope">
            {{ scope.row.startTime }}
          </template>
        </el-table-column>

        <el-table-column align="center"
                         label="失效时间">
          <template slot-scope="scope">
            {{ scope.row.endTime }}
          </template>
        </el-table-column>

        <el-table-column align="center"
                         label="创建时间">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>

        <el-table-column align="center"
                         label="修改时间">
          <template slot-scope="scope">
            {{ scope.row.updateTime }}
          </template>
        </el-table-column>

        <el-table-column align="center"
                         label="状态">
          <template slot-scope="scope">
            <i v-if="scope.row.status == 0" class="el-icon-check"
               style="font-size: 20px; background: #E8F4FF; color: #1890FF"></i>
            <i v-else class="el-icon-close" style="font-size: 20px; background: #FFEDED; color: #FF4949"></i>
          </template>
        </el-table-column>
      </el-table>

      <!--分页-->
      <el-pagination style="margin-top: 25px"
                     @size-change="handleRoleSizeChange"
                     @current-change="handleRoleCurrentChange"
                     :current-page="roleQueryInfo.pageNo"
                     :page-sizes="[10, 20, 30, 50]"
                     :page-size="roleQueryInfo.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="userTotal">
      </el-pagination>

    </el-dialog>

  </el-container>

</template>

<script>
export default {
  name: 'UserManage',
  data() {
    //自定义用户名校验规则
    var validateUsername = (rule, value, callback) => {
      this.$http.get(this.API.checkUserName + '/' + this.addForm.userName).then((resp) => {
        if (resp.data.code === 200) {
          callback()
        } else {
          callback(new Error('用户名已存在'))
        }
      })
    }
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      //查询用户的参数
      queryInfo: {
        'userName': '',
        'trueName': '',
        'status': '',
        'dateRange': null,
        'pageNo': 1,
        'pageSize': 20
      },
      //查询角色的参数
      roleQueryInfo: {
        'roleName': '',
        'status': '',
        'pageNo': 1,
        'pageSize': 10
      },
      dateRange: null,
      //账号状态查询下拉框信息
      status: [
        {
          info: '全部',
          type: ''
        },
        {
          info: '有效',
          type: 0
        },
        {
          info: '无效',
          type: 1
        }
      ],
      //用户信息
      userInfo: [],
      //导出文件信息:
      excelData: [],
      //下拉框所选择的数据
      selected: '',
      //被选择的表格中的行数据
      selectedInTable: [],
      //所有用户的条数
      total: 0,
      //所有用户的条数
      userTotal: 0,
      //添加用户的对话框是否显示
      addTableVisible: false,
      //修改用户信息的对话框是否显示
      updateVisible: false,
      //导入用户对话框是否显示
      ImportVisible: false,
      //添加用户的表单信息
      addForm: {
        'userName': '',
        'password': '',
        'trueName': '',
        'sex': '2',
        'phonenumber': '',
        'email': '',
        'status': '0',
        'remark': ''
      },
      //修改用户的表单信息
      updateForm: {
        'userName': '',
        'password': '',
        'trueName': '',
        'sex': '',
        'phonenumber': '',
        'email': '',
        'status': '',
        'remark': ''
      },
      //添加用户表单的验证规则
      addFormRules: {
        userName: [
          {
            required: true,
            message: '请输入登录用户名',
            trigger: 'blur'
          },
          {
            validator: validateUsername,
            trigger: 'blur'
          },
          {
            pattern: /^[a-zA-Z]\w{5,20}$/,
            message: '用户名由6-20位字母组成'
          }
        ],
        trueName: [
          {
            pattern: /^[\u4E00-\u9FA5A-Za-z]+$/,
            message: '姓名由2-50个英文字母或汉字组成',
            trigger: 'blur'
          },
          {
            required: true,
            min: 2,
            max: 50,
            message: '姓名由2-50个英文字母或汉字组成'
          }
        ],
        password: [
          {
            pattern: /^[A-Za-z0-9]+$/,
            trigger: 'blur',
            message: '密码由6-20位数字或英文字母组成'
          },
          {
            required: true,
            min: 6,
            max: 20,
            message: '密码由6-20位数字或英文字母组成'
          }
        ],
        phonenumber: [
          {
            pattern: /^((0\d{2,3}-\d{7,8})|(1[345789]\d{9}))$/,
            message: '请输入正确的电话号码或者固话号码',
            trigger: 'blur'
          }
        ],
        email: [
          {
            pattern: /^(\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)$/,
            message: '请输入正确的电子邮箱',
            trigger: 'blur'
          }
        ],
        remark: [
          {
            max: 500,
            message: '格式错误，长度应小于500',
            trigger: 'blur'
          }
        ]
      },
      //添加用户表单的验证规则
      updateFormRules: {
        userName: [
          {
            required: true,
            message: '请输入登录用户名',
            trigger: 'blur'
          },
          {
            validator: validateUsername,
            trigger: 'blur'
          },
          {
            pattern: /^[a-zA-Z]\w{5,20}$/,
            message: '用户名由6-20位字母组成'
          }
        ],
        trueName: [
          {
            required: true,
            min: 2,
            max: 50,
            pattern: /^[\u4E00-\u9FA5A-Za-z]+$/,
            message: '姓名由2-50个英文字母或汉字组成',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: false,
            pattern: /^[A-Za-z0-9]+$/,
            trigger: 'blur',
            message: '密码由6-20位数字或英文字母组成'
          }, {
            min: 6,
            max: 20,
            trigger: 'blur',
            message: '密码由6-20位数字或英文字母组成'
          }
        ],
        phonenumber: [
          {
            pattern: /^((0\d{2,3}-\d{7,8})|(1[345789]\d{9}))$/,
            message: '请输入正确的电话号码或者固话号码',
            trigger: 'blur'
          }
        ],
        email: [
          {
            pattern: /^(\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)$/,
            message: '请输入正确的电子邮箱',
            trigger: 'blur'
          }
        ],
        remark: [
          {
            max: 500,
            message: '格式错误，长度应小于500',
            trigger: 'blur'
          }
        ]
      },
      //用户表格信息加载
      loading: true,
      //角色表格信息加载
      roleLoading: true,
      // 用户导入参数
      limitUpload: 1,//限制上传文件的个数
      fileTemp: "",
      file: "",
      fileListUpload: [],
      updateSupport: 0,
      fileFormat: false,
      roleDialogVisible: false,
      //分配角色对话框中表格被选中
      selectedRoleTable: [],
      //所有题目的信息
      roleInfo: [],
      //分配角色的用户ID
      addRoleUserId: ''
    }
  },
  created() {
    this.getUserInfo()
  },
  methods: {
    userRowKeys(row) {
      return row.userId
    },
    roleRowKeys(row) {
      return row.roleId
    },
    //获取用户信息
    getUserInfo(isClear) {
      this.loading = true;
      this.$http.get(this.API.getUserInfo, {params: this.queryInfo}).then((resp) => {
        if (resp.data.code === 200) {
          if (isClear != false) {
            this.$refs.userTable.clearSelection()  //清除复选框选择
          }
          this.userInfo = resp.data.data.users;
          this.total = resp.data.data.total;
          this.loading = false;
        } else {
          this.$notify({
            title: 'Tips',
            message: '获取信息失败',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    //重置搜索条件表单
    resetQuery() {
      this.$refs['queryForm'].resetFields()
      this.dateRange = null
      this.getUserInfo()
    },
    //时间范围搜索
    dateRangeChange(val) {
      if (val != null) {
        this.queryInfo.dateRange = val.join(',')
      } else {
        this.queryInfo.dateRange = null
      }
    },
    //表格某一行被选中
    handleSelectionChange(val) {
      this.selectedInTable = val
    },
    //功能下拉框被选择
    selectChange(val) {
      let tipInfo = ''
      if (val === 'on') {
        tipInfo = '是否继续启用所选用户?'
      } else if (val === 'off') {
        tipInfo = '是否继续禁用所选用户?'
      } else if (val === 'delete') {
        tipInfo = '此操作将永久删除所选用户, 是否继续?'
      }
      this.$confirm(tipInfo, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //清空上一次的操作
        this.selected = ''
        //表格中所选中的用户的id
        let userIds = []
        this.selectedInTable.map(item => {
          userIds.push(item.userId)
        })
        if (val === 'on') {//状态设置为有效
          this.$http.get(this.API.handleUser + '/' + 1, {params: {'userIds': userIds.join(',')}}).then((resp) => {
            if (resp.data.code === 200) {
              //删除成功后,回调更新用户数据
              this.getUserInfo()
              this.$notify({
                title: 'Tips',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: 'Tips',
                message: '操作失败',
                type: 'error',
                duration: 2000
              })
            }
          })
        } else if (val === 'off') {//禁用用户
          this.$http.get(this.API.handleUser + '/' + 2, {params: {'userIds': userIds.join(',')}}).then((resp) => {
            if (resp.data.code === 200) {
              //删除成功后,回调更新用户数据
              this.getUserInfo()
              this.$notify({
                title: 'Tips',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: 'Tips',
                message: '操作失败',
                type: 'error',
                duration: 2000
              })
            }
          })
        } else if (val === 'delete') {//删除用户
          this.$http.get(this.API.handleUser + '/' + 3, {params: {'userIds': userIds.join(',')}}).then((resp) => {
            if (resp.data.code === 200) {
              //删除成功后,回调更新用户数据
              this.getUserInfo()
              this.$notify({
                title: 'Tips',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: 'Tips',
                message: '操作失败',
                type: 'error',
                duration: 2000
              })
            }
          })
        }
        this.getUserInfo()
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    //分页插件的大小改变
    handleSizeChange(val) {
      this.queryInfo.pageSize = val
      this.getUserInfo(false)
    },
    //分页插件的页数
    handleCurrentChange(val) {
      this.queryInfo.pageNo = val
      this.getUserInfo(false)
    },
    //分配角色分页插件的大小改变
    handleRoleSizeChange(val) {
      this.roleQueryInfo.pageSize = val
      this.getRoleInfo(false)
    },
    //角色分页插件的页数
    handleRoleCurrentChange(val) {
      this.roleQueryInfo.pageNo = val
      this.getRoleInfo(false)
    },
    //点击添加按钮
    showAddDialog() {
      this.addTableVisible = true
    },
    //点击修改按钮
    showUpdateDialog(row) {
      this.$nextTick(() => {
        this.updateForm = Object.assign({}, row)
        this.updateForm.password = ''
      })
      this.updateVisible = true
    },
    //添加用户
    addUser() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.$http.post(this.API.addUser, this.addForm).then((resp) => {
            if (resp.data.code === 200) {
              this.getUserInfo()
              this.$notify({
                title: 'Tips',
                message: resp.data.message,
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: 'Tips',
                message: resp.data.message,
                type: 'error',
                duration: 2000
              })
            }
            this.addTableVisible = false
          })
        } else {
          this.$message.error('请检查您所填写的信息是否有误')
          return false
        }
      })
    },
    //修改用户
    updateUser() {
      this.$refs['updateForm'].validate((valid) => {
        if (valid) {
          this.$confirm("是否确认修改用户？", '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$http.post(this.API.updateUser, this.updateForm).then((resp) => {
              if (resp.data.code === 200) {
                this.getUserInfo()
                this.$notify({
                  title: 'Tips',
                  message: resp.data.message,
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: 'Tips',
                  message: resp.data.message,
                  type: 'error',
                  duration: 2000
                })
              }
              this.updateVisible = false
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            });
          });
        } else {
          this.$message.error('请检查您所填写的信息是否有误')
          return false
        }
      })
    },
    //表单信息重置
    resetAddForm() {
      //清空表格数据
      this.$refs['addForm'].resetFields()
    },
    resetUpdateForm() {
      if (this.$refs['updateForm']) {
        this.$nextTick(() => {
          this.$refs['updateForm'].resetFields()
        })
      }
    },
    exportToExcel() {
      this.$confirm('确定下载列表文件?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.excelData = this.userInfo; // 你要导出的数据list。
        this.export2Excel()
      }).catch(() => {
      })
    },
    export2Excel() {
      var _that = this;
      require.ensure([], () => {
        const {export_json_to_excel} = require('../plugins/Export2Excel');// Export2Excel.js文件的位置
        const tHeader = ['用戶名', '姓名', '电子邮箱', '电话', '性别', '创建时间', '修改时间', '账号状态'];//导出的文件表头字段名
        const filterVal = ['userName', 'trueName', 'email', 'phonenumber', 'sex', 'createTime', 'updateTime', 'status'];// 导出的文件数据对应字段名，需要与导出的数据字段相对应
        const list = this.excelData
        list.forEach(item => {   //字符代码转明文
          item.sex = item.sex == 0 ? '男' : item.sex == 1 ? '女' : '未知'
          item.status = item.status == 0 ? '有效' : '无效'
        })
        const data = _that.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, '用户数据表' + Date.now())// 导出的表格名称，根据需要自己命名
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    //导入操作相关方法
    showImportDialog() {
      this.ImportVisible = true
    },
    //下载模板文件
    importTemplate() {
      let a = document.createElement("a");
      a.href = "./static/importTemplate.xlsx";
      a.download = "文件模板.xlsx";
      a.style.display = "none";
      document.body.appendChild(a);
      a.click();
      a.remove();
    },
    handleChange(file, fileList) {
      this.fileTemp = file.raw;
      if (this.fileTemp) {
        //判断文件类别是否是excel
        // console.log(this.fileTemp.type)
        if (this.fileTemp.type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          this.fileTemp.type == "application/vnd.ms-excel") {
          this.fileFormat = true
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误，请删除后重新上传!"
          });
          this.fileFormat = false
        }
      }
    },
    // 提交上传文件
    submitFileForm() {
      if (this.fileFormat) {
        this.$refs.upload.submit();
      } else {
        this.$message({
          type: "warning",
          message: "未选择文件或文件格式错误/(ㄒoㄒ)/~~"
        });
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleRemove(file, fileList) {
      // console.log(file)
      this.fileTemp = null;
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择1个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.ImportVisible = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.message + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getUserInfo();
    },
    //处理角色表格被选中
    handleRoleSectionChange(val) {
      this.selectedRoleTable = val
    },
    //点击分配角色按钮
    showRoleDialog(row) {
      this.addRoleUserId = row.userId
      this.roleDialogVisible = true
      this.getRoleInfo()
    },
    //获取角色信息
    getRoleInfo(isClear) {
      this.roleLoading = true
      this.$http.get(this.API.getRoleInfo, {params: this.roleQueryInfo}).then((resp) => {
        if (resp.data.code === 200) {
          if (isClear != false) {
            this.$refs.roleTable.clearSelection()  //清除复选框选择
          }
          this.roleInfo = resp.data.data.roles;
          this.userTotal = resp.data.data.total;
          this.roleLoading = false;
          this.selectRoleByUserId()
        } else {
          this.$notify({
            title: 'Tips',
            message: '获取信息失败',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    //选中已有角色
    selectRoleByUserId() {
      this.$http.get(this.API.getRoleByUserId, {params: {'userId': this.addRoleUserId}}).then((resp) => {
        if (resp.data.code === 200) {
          this.$nextTick(() => {
            for (let i = 0; i < this.roleInfo.length; i++) {
              for (let j = 0; j < resp.data.data.length; j++) {
                //两个数组做比对,选中的做勾选
                if (this.roleInfo[i].roleId == resp.data.data[j].roleId) {
                  this.$refs.roleTable.toggleRowSelection(this.roleInfo[i], true);
                }
              }
            }
          });
        } else {
          this.$notify({
            title: 'Tips',
            message: '获取角色失败',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    //分配角色
    addRoleToUser() {
      this.$confirm("是否确认分配角色？", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //表格中所选中的角色的id
        let roleIds = []
        this.selectedRoleTable.map(item => {
          roleIds.push(item.roleId)
        })
        this.$http.get(this.API.addRoleToUser + '/' + this.addRoleUserId, {params: {'roleIds': roleIds.join(',')}}).then((resp) => {
          if (resp.data.code === 200) {
            this.roleDialogVisible = false
            this.$notify({
              title: 'Tips',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: 'Tips',
              message: resp.data.message,
              type: 'error',
              duration: 2000
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    //显示删除用户确认框
    showDeleteUserDialog(row) {
      const h = this.$createElement;
      this.$msgbox({
        title: '消息',
        message: h('p', null, [
          h('span', null, '是否确认删除用户： '),
          h('i', {style: 'color: teal'}, row.userName)
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          instance.confirmButtonLoading = false
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = '执行中...';
            this.$http.get(this.API.handleUser + '/' + 3, {params: {'userIds': row.userId}}).then((resp) => {
              if (resp.data.code === 200) {
                //删除成功后,回调更新数据
                this.getUserInfo()
                instance.confirmButtonLoading = false
                done()
                this.$notify({
                  title: 'Tips',
                  message: resp.data.message,
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: 'Tips',
                  message: '操作失败',
                  type: 'error',
                  duration: 2000
                })
              }
            })
          } else {
            done();
          }
        }
      }).catch(() => {
      })
    },
    canSelect(row, index) {
      if (row.userId !== 1) {
        return true
      } else {
        return false
      }
    }
  },
  computed: {
    //监测头部信息的token变化
    headers() {
      return {
        authorization: localStorage.getItem('authorization') || ''
      }
    },
  }
}
</script>

<style scoped lang="scss">
.el-container {
  width: 100%;
  height: 100%;
}

.el-input {
  width: 150px;
}

.el-container {
  animation: leftMoveIn .7s ease-in;
}

@keyframes leftMoveIn {
  0% {
    transform: translateX(-100%);
    opacity: 0;
  }
  100% {
    transform: translateX(0%);
    opacity: 1;
  }
}

.role {
  color: #606266;
}

/deep/ .el-table thead {
  color: rgb(85, 85, 85) !important;
}

/*表格的头部样式*/
/deep/ .has-gutter tr th {
  background: rgb(242, 243, 244);
  color: rgb(85, 85, 85);
  font-weight: bold;
}

.el-table {
  box-shadow: 0 0 1px 1px gainsboro;
}
</style>
